(function() {
    var ps = 'absolute';
    //蛇的构造函数
    function Snake(option) {
        option = option instanceof Object ? option : {};
        this.width = option.width || 20;
        this.height = option.height || 20;
        //身体数据
        this.body = [
            {x: 3, y: 2, color: 'red'},
            {x: 2, y: 2, color: 'blue'},
            {x: 1, y: 2, color: 'blue'},
        ];
        //移动方向
        this.direction = 'right'

        //所有元素
        this.elements = []
    }
    //渲染
    Snake.prototype.render = function(map) {
        for (var i = 0; i < this.body.length; i ++) {
            var piece = this.body[i];

            //设置样式
            var elem = document.createElement('div');
            elem.style.width = this.width + 'px';
            elem.style.height = this.height + 'px';
            elem.style.left = piece.x * this.width + 'px';
            elem.style.top = piece.y * this.height + 'px';
            elem.style.position = ps;
            elem.style.backgroundColor = piece.color;

            //添加到页面上
            map.appendChild(elem);
            this.elements.push(elem);
        }   
    }

    //运动
    Snake.prototype.move = function() {
        //蛇身每一项都要变成上一节的位置
        for (var i = this.body.length - 1; i > 0; i --) {
            this.body[i].x = this.body[i - 1].x;
            this.body[i].y = this.body[i - 1].y;
        }
        //记录蛇头数据
        var head = this.body[0];
        switch(this.direction) {
            case 'right':
                head.x += 1;
                break;
            case 'left':
                head.x -= 1;
                break;
            case 'top':
                head.y -= 1;
                break;
            case 'bottom':
                head.y += 1;
                break;
        }
    }

    //删除
    Snake.prototype.remove = function(map) {
        this.elements.forEach(elem => map.removeChild(elem));
        this.elements = [];
    }

    //暴露Snake构造函数
    window.Snake = Snake
})();
